package com.ccubee.data.transfer.transfer.type;

import com.ccubee.data.transfer.event.ColumnData;
import com.ccubee.data.transfer.types.ColumnType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * 类型上下文
 *
 * @Author ycf
 * @Date 2022/11/14 14:41
 * @Version 1.0
 */
@Component
@Slf4j
public class TypeContext implements ApplicationContextAware {
    private final static Map<ColumnType, IType> I_TYPE_MAP = new HashMap<>(2);

    /**
     * 获取制定类型处理器
     *
     * @param mod 类型
     * @return 结果
     */
    public static IType get(ColumnType mod) {
        return I_TYPE_MAP.get(mod);
    }

    /**
     * 执行
     *
     * @param resultSet  结果集
     * @param columnData 数据
     * @return 结果
     */
    public static Object apply(ColumnData columnData, ResultSet resultSet) {
        return get(columnData.getColumnType()).apply(columnData, resultSet);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(IType.class).forEach((k, v) -> I_TYPE_MAP.put(v.type(), v));
    }
}
